var cloneObj = function(obj)
{
	return JSON.parse(JSON.stringify(obj));
};
var _isAll = function(obj, type)
{
	if(!type || !obj) return;
	return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1] === type; 
};
	var isObj 		= function(obj){return _isAll(obj, 'Object');};
	var isArray 	= function(obj){return _isAll(obj, 'Array');};
	var isFunction 	= function(obj){return _isAll(obj, 'Function');};
	var isString 	= function(obj){return _isAll(obj, 'String');};
	var layout = {};

	/**
	 * Retorna o tweet formatado
	 * @param {Object} json Tweet
	 * @param {String} type Tipo de Timeline
	 * @param {String} name Nome da Timeline
	 */
	layout.tweet = function(json, type, name)
	{
		if(!isObj(json))
			return console.warn('layout.tweet Error: Non Obj', json);

		var 
		Tweet 	= cloneObj(json),
		isRt 	= json.retweeted_status,
		Rt 		= isRt || json;

		Tweet['fav'] = type === 'default' && name === 'favorites' ? 
				'true' : 
					'false';
		
		Tweet['tId']						= Rt.id;				
		Tweet['text']						= Rt.text;
		Tweet['entities']					= Rt.entities;
		Tweet['source']						= Rt.source;
		Tweet['userId'] 					= Rt.user.id;	
		Tweet['userName']					= Rt.user.name;
		Tweet['created_at']					= Rt.created_at;
		Tweet['userScreenName'] 			= Rt.user.screen_name;
		Tweet['userProfileImage'] 			= Rt.user.profile_image_url;
		
		Tweet['protectedClass']				= Rt.user['protected'] ? '' : 'dn' ;
		
		Tweet['inReplyToClass']				= Rt.in_reply_to_status_id ? '' : 'dn';
		Tweet['inReplyToScreenName'] 		= Rt.in_reply_to_screen_name || '';
		Tweet['inReplyToStatusId'] 			= Rt.in_reply_to_status_id || '';	
		
		Tweet['retweetedClass'] 			= isRt ? '' : 'dn';
		Tweet['retweetedByScreenName'] 		= isRt ? json.user.screen_name : '';
		Tweet['retweetedByStatusId'] 		= isRt ? json.id : '';
		Tweet['retweetedCreatedAt'] 		= isRt ? json.created_at : '';	
		
		Tweet['text'] 						= json.text;
		
		return _LAYOUT_TWEET.replaceWithObject(Tweet);
	};
	var
	_LAYOUT_TWEET = 
	'<article class="TweetCon" data-id="{{id}}" data-userId="{{userId}}" data-screenName="{{userScreenName}}">'+
			'<header class="header">'+
			    '<figure class="avatar" title="{{userName}} ({{userScreenName}})">'+
			        '<a data-action="user.profile">'+
			            '<img width="45" height="45" src="{{userProfileImage}}"/>'+
			        '</a>'+
			        '<span class="rts {{retweetedClass}}"></span>'+
			        '<figcaption class="screen_name">'+
			        	'<a class="user" data-action="user.profile">{{userScreenName}}</a>: '+
			        	'<a class="cadeado {{protectedClass}}"></a> '+
			        '</figcaption>'+		        
			    '</figure>'+
			    
			    '<aside class="actions">'+
			        '<span class="favorite"><a class="star" fav="{{fav}}"></a></span>'+
			        '<span class="message"><a class="msg"></a></span>'+
			        '<span class="translate"><a class="trans"></a></span>'+
			    '</aside>'+
			    '<span class="text">{{text}}</span>'+
		    '</header>'+
		    	    	    
		    '<footer>'+
		    	'<div class="separator"></div>'+
			    '<span class="footer">'+
			        '<time class="created_at" datetime="{{created_at}}"><a title="{{tId}}" data-id="{{tId}}" data-datetime="{{created_at}}"></a></time> '+
			        '<span class="via" data-i18n="via"></span> '+
			        '<span class="source"><a>{{source}}</a></span> '+
			        '<span class="in_reply_to {{inReplyToClass}}">'+
			        	'<a data-id="{{inReplyToStatusId}}" data-action="tweet.conversation">'+
			        		'<span data-i18n="in_reply_to:{{inReplyToScreenName}}"></span> '+
			        	'</a>'+
			        '</span> '+
			    '</span> '+
			    
			    '<div class="retweeted {{retweetedClass}}">'+
			        '<span class="retweeted_by" data-i18n="retweeted_by"></span> '+
			        '<span class="screen_name">'+
			        	'<a data-screenName="{{retweetedByScreenName}}" data-action="user.profile" class="user">{{retweetedByScreenName}}</a>'+
			        '</span> '+
			        '<span class="created_at">(<a title="{{retweetedByStatusId}}" data-id="{{retweetedByStatusId}}" data-datetime="{{retweetedCreatedAt}}"></a>)</span> '+
			    '</div>'+
			    
			    '<span class="actionsSub">'+
			        '<span class="retweet"><a data-i18n="retweet"></a></span>'+
			    '</span>'+
			    
			    '<span class="reply_button">'+
			        '<a data-i18n="reply"></a>'+
			    '</span>'+
		    '</footer> '+
	'</article>';
	String.prototype.replaceAll = function(strTarget,strSubString)
	{
	    var strText = this;
	    var intIndexOfMatch = strText.indexOf(strTarget);
	    while(intIndexOfMatch != -1)
	    {
	      strText = strText.replace(strTarget,strSubString);
	      intIndexOfMatch = strText.indexOf(strTarget);
	    }
	    return(strText);
	};
	String.prototype.replaceWithObject = function(obj)
	{
		var str = this;
		for(i in obj)
		{
			str = str.replaceAll('{{'+i+'}}', obj[i]);		
		}
		return str;
	};
onmessage = function(event)
{
	switch(event.data.action){
		case 'getTweets':
			getTweets(event.data.type, event.data.name, event.data.tweets, event.data.options, event.data.returnHtml, event.data.max);
			break;
	}
};

function getTweets( type, name, tweets, options, returnHtml, max )
{
	var
	html 	= '',
	re 		= [],
	i 		= 0,
	lastId;	
	
	for(n in tweets)
	{
		if(i >= max)
			break;
		
		if(options && options.max)
		{
			if(tweets[n].id >= options.max)
				continue;				
		}
		
		if(returnHtml)
		{
			html += 
				type === 'default' && name === 'messages' ? 
						layout.dm(tweets[n], type, name) :
							layout.tweet(tweets[n], type, name);
		
		}
		else
		{
			re[i] = tweets[n];	
		}
		lastId = tweets[n].id;
		i++;
	}
	
	postMessage({
		'action': 'getTweets',
		'result': {'lastId': lastId, 'result': ( returnHtml ? html : re)}		
	});
}